package com.jp.knowledge.activity;

import android.content.Context;
import android.content.Intent;
import android.support.v4.content.LocalBroadcastManager;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.canyinghao.canrefresh.CanRefreshLayout;
import com.google.gson.JsonObject;
import com.google.gson.internal.LinkedTreeMap;
import com.jiayen.util.ToasUtil;
import com.jp.knowledge.R;
import com.jp.knowledge.adapter.TopicDetailAdapter;
import com.jp.knowledge.broad.LocalBroadCast;
import com.jp.knowledge.comm.SlidingActivity;
import com.jp.knowledge.http.HttpHelper;
import com.jp.knowledge.logic.TopicLogic;
import com.jp.knowledge.logic.TopicLogicCallBack;
import com.jp.knowledge.model.IModel;
import com.jp.knowledge.model.ReplyListInfo;
import com.jp.knowledge.model.TopicListInfo;
import com.jp.knowledge.util.JsonUtil;
import com.jp.knowledge.util.L;
import com.jp.knowledge.util.ResultSubscriber;
import com.jp.knowledge.util.TimeUtil;
import com.jp.knowledge.view.KeyBordLayoutListener;

import org.xutils.view.annotation.ViewInject;

import java.util.ArrayList;
import java.util.List;

import jp.wasabeef.glide.transformations.CropCircleTransformation;

/**
 * 话题详情
 */
public class TopicDetailActivity extends SlidingActivity implements ResultSubscriber.OnResultListener, View.OnClickListener {

    private final int REPLY_LIST_CODE = 0x0000000001;//评论回复列表
    private final int REPLY_COMMENT_CODE = 0x0000000002;//评论回复

    @ViewInject(R.id.can_content_view)
    private ListView listView;

    @ViewInject(R.id.m_refresh)
    private CanRefreshLayout mRefresh;


    private TextView prise;
    private TextView talk;


    private TopicDetailAdapter adapter;
    private List<ReplyListInfo> replyList;

    //头部信息
    private View headView;
    private TextView userName;
    private TextView content;
    private ImageView photo;
    private ImageView contentIcon;
    private TextView cotentDesc;

    @ViewInject(R.id.editText)
    private TextView editText;

    @ViewInject(R.id.edit_layout)
    private RelativeLayout editLayout;

    @ViewInject(R.id.edit_content)
    private EditText edit;

    @ViewInject(R.id.send_btn)
    private TextView sendBtn;

    @ViewInject(R.id.shade_view)
    private View shadeView;

    private TextView timeText;

    private InputMethodManager inputManager;
    private String commentId;
    private String infoId;
    private String topicId;
    private String toUid;
    private String toCommentId;
    private String commentContent;
    private String infoPic;//内容图片
    private String infoTitle;//内容标题   用于下一个详情页面介绍
    private String username;
    private String picPhoto;
    private long time;
    private int priseNum;

    private TopicListInfo info;

    private boolean isFresh;//是否是刷新

    private KeyBordLayoutListener keyBordLayoutListener;
    private boolean isToComment;
private LocalBroadcastManager localBroadcastManager;
    private TopicLogic topicLogic;
    @Override
    protected int getResourceId() {
        return R.layout.activity_topic_detail;
    }

    @Override
    protected void init() {

        localBroadcastManager = LocalBroadcastManager.getInstance(mContext);

        info = getIntent().getParcelableExtra("info");
        commentId = getIntent().getStringExtra("commentId");
        infoId = getIntent().getStringExtra("infoId");
        topicId = getIntent().getStringExtra("topicId");
        toUid = getIntent().getStringExtra("toUid");
        toCommentId = getIntent().getStringExtra("toCommentId");
        commentContent= getIntent().getStringExtra("content");
        infoPic = getIntent().getStringExtra("info_icon");
        infoTitle = getIntent().getStringExtra("info_title");
        username = getIntent().getStringExtra("username");
        picPhoto = getIntent().getStringExtra("pic");
        time = getIntent().getLongExtra("time",0);
        priseNum=getIntent().getIntExtra("prise",0);


        headView = getLayoutInflater().inflate(R.layout.topic_detail_item_head, null);
        userName = (TextView) headView.findViewById(R.id.name);
        content = (TextView) headView.findViewById(R.id.content);
        cotentDesc = (TextView) headView.findViewById(R.id.content_desc);
        photo = (ImageView) headView.findViewById(R.id.photo);
        contentIcon = (ImageView) headView.findViewById(R.id.content_icon);
        prise = (TextView) headView.findViewById(R.id.head_prise);
        talk= (TextView) headView.findViewById(R.id.head_talk);
        timeText= (TextView) headView.findViewById(R.id.time);

        setHeadData();

        shadeView.setOnClickListener(this);
        listView.addHeaderView(headView);
        replyList = new ArrayList<>();
        adapter = new TopicDetailAdapter(mContext, replyList);
        adapter.setTopicId(topicId);
        adapter.setInfoid(infoId);
        listView.setAdapter(adapter);


        editText.setHint("回复"+username+":");
        editText.setOnClickListener(this);
        sendBtn.setOnClickListener(this);

        getReplyList(0);

        mRefresh.setLoadMoreEnabled(false);
        mRefresh.setRefreshEnabled(false);
        mRefresh.setOnLoadMoreListener(new CanRefreshLayout.OnLoadMoreListener() {
            @Override
            public void onLoadMore() {
                getReplyList(1);
            }
        });




        keyBordLayoutListener= new KeyBordLayoutListener();
        keyBordLayoutListener.setRootView(editLayout);
        keyBordLayoutListener.setListener(new KeyBordLayoutListener.KeyBordListener() {
            @Override
            public void onHideKeyboard() {
                L.e("onHideKeyboard");
                editLayout.setVisibility(View.GONE);
                shadeView.setVisibility(View.GONE);
                edit.setText("");//清空
            }

            @Override
            public void onShowKeyboard() {
                L.e("onShowKeyboard");
                editLayout.setVisibility(View.VISIBLE);
                shadeView.setVisibility(View.VISIBLE);
            }
        });
        editLayout.getViewTreeObserver().addOnGlobalLayoutListener(keyBordLayoutListener);


        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
                isToComment = true;
                if(replyList!=null&&position>0){
                    ReplyListInfo info = replyList.get(position-1);
                    String replyName = info.getNickName();
                     toUid = info.getUid();
                     toCommentId = info.getCommentId();
                     edit.setHint("回复"+replyName);
                    showTopicEdit();
                }
            }
        });


        if(info!=null){
            if(info.getIsPraise()==1){
                prise.setCompoundDrawablesWithIntrinsicBounds(getResources().getDrawable(R.mipmap.toutiaoxiangqingyidianzan),null,null,null);
            }else{//说明是没有点赞的
               prise.setOnClickListener(this);
                prise.setCompoundDrawablesWithIntrinsicBounds(getResources().getDrawable(R.mipmap.toutiaoxiangqingzan),null,null,null);
            }
        }

        talk.setText(info.getReplyNum()+"");

        topicLogic = new TopicLogic(mContext, new TopicLogicCallBack() {
            @Override
            public void priseSuccess(int position) {
                info.setIsPraise(1);
//                super.priseSuccess(position);
                prise.setText((Integer.valueOf(prise.getText().toString())+1)+"");
                prise.setCompoundDrawablesWithIntrinsicBounds(getResources().getDrawable(R.mipmap.toutiaoxiangqingyidianzan),null,null,null);

                Intent intentFilter = new Intent(LocalBroadCast.PRISE_BROAD);

                localBroadcastManager.sendBroadcast(intentFilter);
            }
        });

        timeText.setText(TimeUtil.friendly_time(time));
        prise.setText(priseNum+"");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        editLayout.getViewTreeObserver().removeOnGlobalLayoutListener(keyBordLayoutListener);
    }

    /**
     * 设置头部信息
     */
    private void setHeadData() {
        userName.setText(username);
        content.setText(commentContent);
        cotentDesc.setText(infoTitle);

        Glide.with(mContext).load(picPhoto).bitmapTransform(new CropCircleTransformation(mContext))
                .fitCenter().placeholder(R.mipmap.toutiaoxiangqingmo)
                .override(30,30).into(photo);

        Glide.with(mContext).load(infoPic).bitmapTransform(new CropCircleTransformation(mContext))
                .fitCenter().placeholder(R.mipmap.morentuzhengfangxing)
                .override(40,40).into(contentIcon);
    }


    /**
     * 获取回复列表
     *
     * @param mode
     */
    private void getReplyList(int mode) {
        if(mode==0){
            isFresh=true;
        }else{
            isFresh=false;
        }
        JsonObject param = new JsonObject();
        param.addProperty("commentId", commentId);
        long time = 0;
        if (replyList != null && replyList.size() > 0) {
            if (mode == 0) {
                time = replyList.get(0).getTime();
            } else {
                time = replyList.get(replyList.size() - 1).getTime();
            }
        }
        param.addProperty("time", time);
        param.addProperty("mode", mode);
        HttpHelper.getInstance(mContext).replyList(param, REPLY_LIST_CODE, this);
    }

    @Override
    public void onStart(int requestType) {
            loading.show();
    }

    @Override
    public void onCompleted(int requestType) {
            mRefresh.loadMoreComplete();
        loading.cancel();
    }

    @Override
    public void onError(int requestType) {
        mRefresh.loadMoreComplete();
        loading.cancel();
    }

    @Override
    public void onNext(IModel data, int requestType) {
        int code = data.getErrcode();
        if (requestType == REPLY_LIST_CODE) {
            if (code == 0) {
                List<ReplyListInfo> temp = JsonUtil.getInstance().listMapToObject((ArrayList<LinkedTreeMap<String, Object>>) data.getData(), ReplyListInfo.class);
                if(temp!=null&&temp.size()>0){
                    if(replyList==null)replyList=new ArrayList<>();
                    if(isFresh){
//                        int size = temp.size();
//                        for (int i = 0; i < size; i++) {
//                            replyList.add(i,temp.get(i));
//                        }
                        replyList=temp;
                    }else{
                        replyList.addAll(temp);
                    }
                }
                adapter.updataAdapter(replyList);
            } else {
                ToasUtil.toast(mContext, "获取回复数据失败");
            }

        }else if(requestType==REPLY_COMMENT_CODE){
            if (code == 0) {
                    getReplyList(0);
            }
        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.editText://发表
                //此处改为开启话题
//                openTopic();
                edit.setHint("回复"+username);
                isToComment=false;
                showTopicEdit();
                break;
            case R.id.send_btn://发送
                addComment();//添加评论
                break;
            case R.id.head_prise://点赞
                topicLogic.topicPrise(info.getInfoId(),topicId,info.getCommentId(),0);
                break;
            case R.id.shade_view://点击隐藏软键盘
                    hideSoftAndEdit();
                break;
            default:
                break;
        }
    }


    /**
     * 隐藏软键盘
     */
    public void hideSoftAndEdit() {
        if (editLayout.getVisibility() == View.VISIBLE) {
            editLayout.setVisibility(View.GONE);
            if (inputManager!=null&&inputManager.isActive())
                inputManager.hideSoftInputFromWindow(edit.getWindowToken(), 0);

        }
    }

    /**
     * 添加回复评论
     */
    private void addComment() {
        String tUid ="";
        String tCommentId ="";

        if(isToComment){//是回复别人的评论
            tUid=toUid;
            tCommentId=toCommentId;
        }

        JsonObject param = new JsonObject();
        param.addProperty("infoId", infoId);
        param.addProperty("topicId", topicId);
        param.addProperty("commentId", commentId);
        param.addProperty("toUid", tUid);
        param.addProperty("toCommentId", tCommentId);
        param.addProperty("content", edit.getText().toString());
        HttpHelper.getInstance(mContext).replyTopic(param, REPLY_COMMENT_CODE, this);
    }


    private void showTopicEdit() {
        editLayout.setVisibility(View.VISIBLE);
        edit.requestFocus();
        toggleInput();
    }

    /**
     * 显示或者隐藏键盘
     */
    private void toggleInput() {
        if (inputManager == null)
            inputManager = (InputMethodManager) edit.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        inputManager.toggleSoftInput(0, InputMethodManager.SHOW_FORCED);

    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if(event.getAction() == MotionEvent.ACTION_DOWN){
            if(getCurrentFocus()!=null && getCurrentFocus().getWindowToken()!=null){
                inputManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
            }
        }
        return super.onTouchEvent(event);
    }

}
